import submitRecordService, {
	type RecordQueryParams,
	type SubmitRecord,
	RecordStatus,
} from "@/api/services/submitRecordService";
import {
	Button,
	Card,
	Col,
	DatePicker,
	Image,
	Row,
	Select,
	Table,
	Tag,
	message,
	Spin,
	Empty,
	Pagination,
	Tooltip,
	Input,
} from "antd";
import { useEffect, useState, useCallback } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useResponsive } from "ahooks";
import dayjs from "dayjs";
import { DownloadOutlined } from "@ant-design/icons";
import InfoDrawer from "./info";
import FieldDisplay from "./components/FieldDisplay";
import TaskDetailDrawer from "./components/TaskDetailDrawer";
import taskService, { TaskItem } from "@/api/services/taskService";
import { Drawer, Typography, Space, Card as AntdCard } from "antd";
import { Iconify } from "@/components/icon";
import parse from "html-react-parser";

const { RangePicker } = DatePicker;

const statusOptions = [
	{ label: "全部", value: RecordStatus.ALL },
	{ label: "审核中", value: RecordStatus.PENDING },
	{ label: "已通过", value: RecordStatus.APPROVED },
	{ label: "未通过", value: RecordStatus.REJECTED },
];

const SubmitRecordsPage = () => {
	const navigate = useNavigate();
	const location = useLocation();
	const { mobile } = useResponsive();
	const [loading, setLoading] = useState(false);
	const [records, setRecords] = useState<SubmitRecord[]>([]);
	const [total, setTotal] = useState(0);
	const [current, setCurrent] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [queryParams, setQueryParams] = useState<RecordQueryParams>({
		status: RecordStatus.ALL,
		keyword: '',
	});
	const [selectedStatus, setSelectedStatus] = useState<RecordStatus>(
		RecordStatus.ALL,
	);
	const [timeRange, setTimeRange] = useState<any>();
	const [reviewTimeRange, setReviewTimeRange] = useState<any>();
	const [infoDrawerVisible, setInfoDrawerVisible] = useState(false);
	const [selectedRecord, setSelectedRecord] = useState<SubmitRecord | null>(
		null,
	);
	const [taskOptions, setTaskOptions] = useState<
		{ label: string; value: number }[]
	>([]);
	const [selectedTask, setSelectedTask] = useState<TaskItem | null>(null);
	const [taskDetailVisible, setTaskDetailVisible] = useState(false);

	// 获取任务列表
	const fetchTaskOptions = async () => {
		try {
			const res = await taskService.taskList({
				page: 1,
				pageSize: 100,
			});
			const options = res.items.map((task: any) => ({
				label: task.title,
				value: task.id,
			}));
			setTaskOptions(options);
		} catch (error) {
			console.error("获取任务列表失败:", error);
		}
	};

	useEffect(() => {
		fetchTaskOptions();
	}, []);

	const handleTaskChange = (task_id: number) => {
		setQueryParams((prev) => ({
			...prev,
			task_id,
			current: 1,
		}));
	};

	const fetchRecords = async (params: RecordQueryParams) => {
		try {
			setLoading(true);
			const { items, total } = await submitRecordService.getRecords({
				...params,
				current: params.current || current,
				pageSize: params.pageSize || pageSize,
			});
			console.log(items, 'items')
			setRecords(items);
			setTotal(total);
		} catch (error: any) {
			message.error(error.message || "获取记录失败");
		} finally {
			setLoading(false);
		}
	};

	const handleExport = async () => {
		try {
			setLoading(true);
			const response = await submitRecordService.exportRecords(queryParams);
			const { url, filename } = response;

			if (mobile) {
				// 移动端跳转到浏览器下载
				window.location.href = url;
			} else {
				// PC端下载
				const link = document.createElement("a");
				link.href = url;
				link.download = filename;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
			}
		} catch (error: any) {
			message.error(error.message || "导出记录失败");
		} finally {
			setLoading(false);
		}
	};

	const handleStatusChange = (status: RecordStatus) => {
		setQueryParams((prev) => ({
			...prev,
			status,
			current: 1, // 切换状态时重置页码
		}));
		setSelectedStatus(status);
	};

	const handleSubmitTimeChange = (dates: any) => {
		const [start, end] = dates || [];
		setTimeRange(dates);
		setQueryParams((prev) => ({
			...prev,
			start_time: start?.unix(),
			end_time: end?.unix(),
			current: 1,
		}));
	};

	const handleReviewTimeChange = (dates: any) => {
		const [start, end] = dates || [];
		setReviewTimeRange(dates);
		setQueryParams((prev) => ({
			...prev,
			review_start_time: start?.unix(),
			review_end_time: end?.unix(),
			current: 1,
		}));
	};

	const handleKeywordChange = (value: string) => {
		setQueryParams(prev => ({
			...prev,
			keyword: value
		}));
		// 如果需要立即触发搜索，可以在这里调用搜索函数
	};

	const getStatusColor = (status: number) => {
		switch (status) {
			case RecordStatus.PENDING:
				return "warning"; // 审核中使用警告色
			case RecordStatus.APPROVED:
				return "success"; // 审核通过使用成功色
			case RecordStatus.REJECTED:
				return "error"; // 审核失败使用错误色
			default:
				return "default";
		}
	};

	const getStatusText = (status: number) => {
		switch (status) {
			case RecordStatus.PENDING:
				return "审核中";
			case RecordStatus.APPROVED:
				return "已通过";
			case RecordStatus.REJECTED:
				return "未通过";
			default:
				return "未知";
		}
	};

	// 重置页面状态
	const resetPageState = useCallback(() => {
		setCurrent(1);
		setPageSize(10);
		setQueryParams({ status: RecordStatus.ALL });
		setSelectedStatus(RecordStatus.ALL);
		setTimeRange(null);
		setReviewTimeRange(null);
	}, []);

	// 监听查询参数变化
	useEffect(() => {
		fetchRecords(queryParams);
	}, [queryParams]);

	// 监听分页变化
	useEffect(() => {
		if (current && pageSize) {
			const newParams = {
				...queryParams,
				current,
				pageSize,
			};
			setQueryParams(newParams); // 更新查询参数，触发上面的 effect
		}
	}, [current, pageSize]);

	// 初始化加载
	useEffect(() => {
		resetPageState();
		const initialParams = {
			status: RecordStatus.ALL,
			current: 1,
			pageSize: 10,
		};
		setQueryParams(initialParams);
	}, [location.pathname]);

	return (
		<div className="min-h-screen bg-gray-50">
			<Card bordered={false} bodyStyle={{ padding: mobile ? "12px" : "24px" }}>
				{/* 搜索区域 */}
				<div className={`${mobile ? "space-y-3" : ""}`}>
					<Row gutter={[12, 12]} align="middle">
						<Col xs={24} sm={8} md={6}>
							<Select
								placeholder="选择状态"
								value={queryParams.status}
								onChange={handleStatusChange}
								options={statusOptions}
								className="w-full"
								size={mobile ? "large" : "middle"}
							/>
						</Col>
						<Col xs={24} sm={8} md={6}>
							<Input
								placeholder="请输入关键词搜索"
								allowClear
								className="w-full"
								size={mobile ? "large" : "middle"}
								onChange={(e) => {
									// 这里需要在组件中添加相应的处理函数
									handleKeywordChange(e.target.value);
								}}
							/>
						</Col>
						{!mobile && (
							<>
								<Col xs={24} sm={8}>
									<Select
										placeholder="选择任务"
										allowClear
										showSearch
										optionFilterProp="label"
										onChange={handleTaskChange}
										options={taskOptions}
										className="w-full"
										size={mobile ? "large" : "middle"}
									/>
								</Col>
								<Col xs={24} sm={12} md={8} lg={6}>
									<RangePicker
										className="w-full"
										placeholder={["提交开始时间", "提交结束时间"]}
										value={timeRange}
										onChange={handleSubmitTimeChange}
										allowClear
										showTime={{ format: 'HH:mm:ss' }}
									/>
								</Col>
								<Col xs={24} sm={12} md={8} lg={6}>
									<RangePicker
										className="w-full"
										placeholder={["审核开始时间", "审核结束时间"]}
										value={reviewTimeRange}
										onChange={handleReviewTimeChange}
										allowClear
										showTime={{ format: 'HH:mm:ss' }}
									/>
								</Col>
								<Col xs={24} sm={8}>
									<Button
										type="primary"
										icon={<DownloadOutlined />}
										onClick={handleExport}
										loading={loading}
										className="w-full"
										size={mobile ? "large" : "middle"}
									>
										导出记录
									</Button>
								</Col>
							</>
						)}
					</Row>

					{/* 移动端的时间选择器 */}
					{mobile && (
						<Row gutter={[12, 12]}>
							<Col span={24}>
								<RangePicker
									placeholder={["开始时间", "结束时间"]}
									onChange={handleSubmitTimeChange}
									className="w-full"
									size="large"
									showTime={{ format: 'HH:mm:ss' }}
								/>
							</Col>
							<Col span={24}>
								<RangePicker
									placeholder={["审核开始时间", "审核结束时间"]}
									onChange={handleReviewTimeChange}
									className="w-full"
									size="large"
									showTime={{ format: 'HH:mm:ss' }}
								/>
							</Col>
						</Row>
					)}
				</div>

				{/* 数据列表 */}
				<div className={`${mobile ? "mt-3" : "mt-4"} pb-16`}>
					{loading ? (
						<div className="flex justify-center py-8">
							<Spin size="large" />
						</div>
					) : (
						<div className={`${mobile ? "space-y-3" : "space-y-4"}`}>
							{records.map((record) => (
								<Card
									key={record.id}
									className="cursor-pointer hover:shadow-md transition-all duration-300 border-l-4"
									style={{
										borderLeftColor:
											getStatusColor(record.status) === "warning"
												? "#faad14"
												: getStatusColor(record.status) === "success"
													? "#52c41a"
													: getStatusColor(record.status) === "error"
														? "#ff4d4f"
														: "#d9d9d9",
									}}
									bodyStyle={{ padding: mobile ? "12px" : "16px" }}
									onClick={() => {
										if (record.task) {
											setSelectedTask(record.task as TaskItem);
											setTaskDetailVisible(true);
										}
									}}
								>
									<div className="flex-1">
										<div className="flex items-center mb-3 gap-2 flex-wrap">
											<div className="flex items-center min-w-0 flex-1">
												<span className="text-gray-400 text-sm shrink-0 mr-2">
													#{record.id}
												</span>
												<div
													className={`font-medium ${mobile ? "text-base" : "text-lg"} truncate`}
												>
													{record?.task?.title || "未知任务"}
												</div>
											</div>
											<Tag
												color={getStatusColor(record.status)}
												className="whitespace-nowrap shrink-0"
											>
												{record.status === RecordStatus.REJECTED &&
												record.remark ? (
													<Tooltip
														title={record.remark}
														color="#ff4d4f"
														placement={mobile ? "bottomRight" : "right"}
													>
														<span>{getStatusText(record.status)}</span>
													</Tooltip>
												) : (
													getStatusText(record.status)
												)}
											</Tag>
										</div>

										<div
											className={`grid ${mobile ? "grid-cols-1" : "grid-cols-2"} gap-2 text-sm text-gray-500 mb-3`}
										>
											<div className="flex items-center">
												<span className="mr-2 w-16 shrink-0">金额：</span>
												<span className="text-primary font-medium">
													¥{record?.price || "0.00"}
												</span>
											</div>
											{record.user?.mobile && (
												<div className="flex items-center">
													<span className="mr-2 w-16 shrink-0">手机：</span>
													<span className="text-gray-800">
														{record.user.mobile}
													</span>
												</div>
											)}
										</div>

										<div className={`space-y-1.5 text-sm text-gray-400 mb-3`}>
											<div className="flex items-center">
												<span className="mr-2 w-[4.5rem] shrink-0">
													提交时间：
												</span>
												<span>{record.createtime_text}</span>
											</div>
											{record.reviewtime && (
												<div className="flex items-center">
													<span className="mr-2 w-[4.5rem] shrink-0">
														反馈时间：
													</span>
													<span>
														{dayjs(record.reviewtime * 1000).format(
															"YYYY-MM-DD HH:mm:ss",
														)}
													</span>
												</div>
											)}
										</div>

										{record.remark && (
											<div className="mt-2 p-3 bg-orange-50 border border-orange-200 rounded-md">
												<div className="text-orange-500 font-medium mb-1 flex items-center">
													<span className="mr-1">📝</span>
													反馈意见
												</div>
												<div className="text-gray-700 break-all">
													{record.remark}
												</div>
											</div>
										)}

										{record.value && record.value.length > 0 && (
											<div className={`bg-gray-50 rounded-lg ${mobile ? "p-3" : "p-4"}`}>
												<div className="space-y-3">
													{record.value.map((item, index) => (
														<div 
															key={`${record.id}-${item.id}-${index}`} 
															className="text-sm"
														>
															<div className="text-gray-500 mb-1">
																{item.field?.field_label || "未知字段"}：
															</div>
															<div className="text-gray-800 flex-1 break-all">
																<FieldDisplay
																	fieldType={item.field?.field_type || "text"}
																	value={item.value}
																/>
															</div>
														</div>
													))}
												</div>
											</div>
										)}

										{record.status === RecordStatus.REJECTED &&
											record.remark && (
												<div className="mt-3 text-sm">
													{/* <span className="text-red-500 font-medium">审核未通过：</span>
												<span className="text-red-500">{record.remark}</span> */}
												</div>
											)}
									</div>
								</Card>
							))}
							{!loading && records.length === 0 && (
								<Empty description="暂无记录" className="py-8" />
							)}
						</div>
					)}

					{/* 分页器 */}
					{!loading && records.length > 0 && (
						<div className="flex justify-center mt-4">
							<Pagination
								current={current}
								pageSize={pageSize}
								total={total}
								onChange={(page, size) => {
									setCurrent(page);
									setPageSize(size);
								}}
								showSizeChanger
								showQuickJumper
								showTotal={(total) => `共 ${total} 条`}
							/>
						</div>
					)}
				</div>

				{/* 移动端底部操作栏 */}
				{mobile && (
					<div className="fixed bottom-0 left-0 right-0 px-3 py-2 bg-white border-t">
						<Button
							type="primary"
							icon={<DownloadOutlined />}
							onClick={handleExport}
							loading={loading}
							className="w-full"
							size="large"
						>
							导出记录
						</Button>
					</div>
				)}
			</Card>
			<InfoDrawer
				visible={!!selectedRecord}
				record={selectedRecord}
				onClose={() => {
					setSelectedRecord(null);
				}}
			/>

			<TaskDetailDrawer
				visible={taskDetailVisible}
				task={selectedTask}
				onClose={() => setTaskDetailVisible(false)}
			/>
		</div>
	);
};

export { SubmitRecordsPage as SubmitRecords };
export default SubmitRecordsPage;
